Labeled Elements in Initializers

Contents|Index|Previous|Next
Labeled elements in initializers

Standard C requires the elements of an initializer to appear in a fixed order, the same as the order of the elements in the array or structure being initialized. In GNU C you can give the elements in any order, specifying the array indices or structure field names they apply to. This extension is not implemented in GNU C++. To specify an array index, write ‘[index]’ or ‘[index]=’ before the element value. Use the following example.

    int a[6] = { [4] 29, [2] = 15 };

The previous specification is equivalent to the following.

    int a[6] = { 0, 0, 15, 0, 29, 0 };

The index values must be constant expressions, even if the array being initialized is automatic. To initialize a range of elements to the same value, write ‘[ first... last]=value’. Use the following example.

    int widths[] = { [0 ... 9] = 1, [10 ... 99] = 2, [100] = 3 };

Note:
The length of the array is the highest value specified + 1.

In a structure initializer, specify the name of a field to initialize with ‘fieldname:’ before the element value. For example given struct point { int x, y; };, the initialization, struct point p = { y: yvalue, x: xvalue }; is equivalent to: point p = { xvalue, yvalue struct };.

Another syntax which has the same meaning is ‘.fieldname=’ as in the following statement.

    struct point p = { .y = yvalue, .x = xvalue };

You can also use an element label (with either the colon syntax or the period-equal syntax) when initializing a union, to specify which element of the union should be used. For example, the following will convert 4 to a double to store it in the union using the second element.

    union foo { int i; double d; };

    union foo f = { d: 4 };

By contrast, casting 4 to type union foo would store it into the union as the integer ‘i’, since it is an integer. (See Cast to a union type.)

You can combine this technique of naming elements with ordinary C initialization of successive elements. Each initializer element that does not have a label applies to the next consecutive element of the array or structure. For example, int a[6] = { [1] = v1, v2, [4] = v4 }; is equivalent to: int a[6] = { 0, v1, v2, 0, v4, 0 };.

Labeling the elements of an array initializer is especially useful when the indices are characters or belong to an enum type, as in the following example.

    int whitespace[256]
      = { ['  '] = 1, ['\t'] = 1, ['\h'] = 1,
          ['\f'] = 1, ['\n'] = 1, ['\r'] = 1 };

Top|Contents|Index|Previous|Next